<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <div class="search-header">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入商品名称"
        size="large"
        class="search-input"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </template>
      </el-input>
    </div>

    <!-- 搜索历史和热门搜索 -->
    <div v-if="!hasSearched" class="search-suggestions">
      <div class="search-history" v-if="searchHistory.length > 0">
        <h3>搜索历史</h3>
        <div class="tag-list">
          <el-tag
            v-for="(item, index) in searchHistory"
            :key="index"
            @click="searchByKeyword(item)"
            closable
            @close="removeFromHistory(index)"
          >
            {{ item }}
          </el-tag>
        </div>
      </div>

      <div class="hot-searches">
        <h3>热门搜索</h3>
        <div class="tag-list">
          <el-tag
            v-for="(item, index) in hotSearches"
            :key="index"
            type="success"
            @click="searchByKeyword(item)"
          >
            {{ item }}
          </el-tag>
        </div>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div v-if="hasSearched" class="search-results">
      <!-- 搜索信息 -->
      <div class="search-info">
        <span>搜索"{{ currentKeyword }}"，共找到 {{ total }} 个结果</span>
        <div class="sort-options">
          <el-radio-group v-model="sortType" @change="handleSortChange">
            <el-radio-button label="default">综合</el-radio-button>
            <el-radio-button label="sales">销量</el-radio-button>
            <el-radio-button label="price_asc">价格↑</el-radio-button>
            <el-radio-button label="price_desc">价格↓</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <!-- 商品列表 -->
      <div v-loading="loading" class="products-grid">
        <product-card
          v-for="product in products"
          :key="product.id"
          :product="product"
        />
      </div>

      <!-- 空状态 -->
      <el-empty v-if="!loading && products.length === 0" description="没有找到相关商品">
        <el-button type="primary" @click="goToProducts">浏览全部商品</el-button>
      </el-empty>

      <!-- 分页 -->
      <div v-if="total > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 48]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import ProductCard from '@/components/ProductCard.vue'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()

// 搜索相关数据
const searchKeyword = ref('')
const currentKeyword = ref('')
const hasSearched = ref(false)
const loading = ref(false)

// 商品数据
const products = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)
const sortType = ref('default')

// 搜索历史和热门搜索
const searchHistory = ref([])
const hotSearches = ref([
  'iPhone 15',
  '华为 Mate 60',
  '小米14',
  '笔记本电脑',
  '无线耳机',
  '智能手表',
  '平板电脑',
  '游戏手柄'
])

// 监听路由变化
watch(() => route.query.keyword, (newKeyword) => {
  if (newKeyword && newKeyword !== currentKeyword.value) {
    searchKeyword.value = newKeyword
    handleSearch()
  }
}, { immediate: true })

// 搜索商品
const searchProducts = async () => {
  if (!currentKeyword.value.trim()) return

  loading.value = true
  try {
    const res = await request.get('/products', {
      params: {
        keyword: currentKeyword.value,
        page: currentPage.value,
        size: pageSize.value,
        sort: sortType.value
      }
    })

    if (res && res.code === 200 && res.data) {
      products.value = res.data.content || []
      total.value = res.data.totalElements || 0
    }
  } catch (error) {
    console.error('搜索商品失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  const keyword = searchKeyword.value.trim()
  if (!keyword) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  currentKeyword.value = keyword
  hasSearched.value = true
  currentPage.value = 1

  // 添加到搜索历史
  addToHistory(keyword)

  // 更新URL
  router.push({
    path: '/home/search',
    query: { keyword }
  })

  // 执行搜索
  searchProducts()
}

// 通过关键词搜索
const searchByKeyword = (keyword) => {
  searchKeyword.value = keyword
  handleSearch()
}

// 添加到搜索历史
const addToHistory = (keyword) => {
  const history = [...searchHistory.value]
  const index = history.indexOf(keyword)
  
  if (index > -1) {
    history.splice(index, 1)
  }
  
  history.unshift(keyword)
  
  if (history.length > 10) {
    history.pop()
  }
  
  searchHistory.value = history
  localStorage.setItem('searchHistory', JSON.stringify(history))
}

// 从历史记录中移除
const removeFromHistory = (index) => {
  searchHistory.value.splice(index, 1)
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
}

// 排序变化
const handleSortChange = () => {
  currentPage.value = 1
  searchProducts()
}

// 分页变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  searchProducts()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  searchProducts()
}

// 跳转到商品列表
const goToProducts = () => {
  router.push('/home/products')
}

// 页面初始化
onMounted(() => {
  // 加载搜索历史
  const history = localStorage.getItem('searchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }
})
</script>

<style scoped>
.search-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.search-header {
  margin-bottom: 30px;
}

.search-input {
  max-width: 600px;
}

.search-suggestions {
  margin-bottom: 30px;
}

.search-suggestions h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-list .el-tag {
  cursor: pointer;
}

.search-results {
  margin-top: 20px;
}

.search-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 1200px) and (min-width: 769px) {
  .products-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .search-info {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .products-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }
}
</style>
